package com.atguigu.day07;

import com.atguigu.utils.ClickEvent;
import com.atguigu.utils.ClickSource;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoFlatMapFunction;
import org.apache.flink.util.Collector;

// 查询流
// 在socket中输入要查询的字符串
// 将点击流中符合查询条件的事件过滤出来
public class Example5 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment
                .getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<String> queryStream =
                env.socketTextStream("localhost", 9999);

        DataStreamSource<ClickEvent> clickStream =
                env.addSource(new ClickSource());

        clickStream.keyBy(r -> r.url)
                // 广播之前要先将并行度设置为1
                // 因为要把数据流上的数据按照顺序广播出去
                .connect(queryStream.setParallelism(1).broadcast())
                .flatMap(new Query())
                .print();

        env.execute();
    }

    // CoFlatMapFunction<IN1, IN2, OUT>
    // flatMap1和flatMap2没有特定的执行顺序
    // 第一条流的数据过来就触发flatMap1
    // 第二条流的数据过来就触发flatMap2
    public static class Query implements
            CoFlatMapFunction<ClickEvent, String, ClickEvent> {
        // 用来保存来自第二条流的查询字符串
        private String queryString = "";
        // flatMap1处理来自第一条流（clickStream）的事件
        @Override
        public void flatMap1(ClickEvent value, Collector<ClickEvent> out) throws Exception {
            // 如果数据的username字段等于查询字符串queryString，就传播下去
            if (value.username.equals(queryString)) out.collect(value);
        }

        // flatMap2处理来自第二条流（queryStream）的事件
        @Override
        public void flatMap2(String value, Collector<ClickEvent> out) throws Exception {
            // 将查询字符串保存到queryString变量中
            queryString = value;
        }
    }
}
